<?php

namespace app\admin\service\mysql;

use app\admin\service\BaseService;
use app\common\utils\MysqlUtils;

class MysqlToolsService extends BaseService
{
    /**
     * 数据表的数据值转换为json格式
     * @param string $table_name 数据表名
     * @param bool $include_comment 是否包含注释
     * @return string|null
     */
    public static function tableValueToJson(string $table_name, bool $include_comment = false): ?string
    {
        $table_field = MysqlUtils::getTableField($table_name);
        if (empty($table_field)) {
            return null;
        }

        //查询示例数据
        $where = "1=1 AND is_deleted=0";
        $data_info = MysqlUtils::getDataInfo($table_name, $where);
        if (empty($data_info)) { //如果没查到数据,则返回自定义配置的字段值
            $struct = [];
            foreach ($table_field as $key => $item) {
                $struct[$key] = $item['default_value'];
            }
            $data_info = $struct;
        }

        //返回json
        $json = echoJson($data_info);
        if(!$include_comment){
            return $json;
        }

        //给返回的json追加注释
        $json_format = preg_replace('/\{|\}/', '', $json); //对json中的 花括号 替换为空
        $json_format_array = explode(',', $json_format); //按照逗号分隔
        foreach ($json_format_array as &$v) {
            $v_item = explode(':', $v);
            $v_item_key = str_replace('"', '', $v_item[0]);

            //追加注释
            $v_item_comment = $table_field[$v_item_key]['name'] ?? '';
            $v .= ", //" . $v_item_comment;
        }
        $json_new = "{\n";
        $json_new .= implode("\n", $json_format_array) . "\n";
        $json_new .= "}\n";
        return $json_new;
    }

}